<template>
	<view class="page-container back-white">
		<!-- 头部 -->
		<view class="head-box">
			<!-- 商家信息 -->
			<view class="info-box col-box sb">
				<view class="row-box">
					<u-avatar :src="merchant.icon" size="92" mode="square"></u-avatar>
					<text class="s30 bold ml-base">{{ merchant.name }}</text>
				</view>
				<view class="row-box mt-10">
					<text class="s26 orange mr-base"><text class="orange bold">5.0</text>分</text>
					<text class="s26 grey-dark">预计45分钟送达</text>
				</view>
				<view class="row-box mt-10">
					<text class="s26">营业时间：{{ merchant.beginTime }}-{{ merchant.endTime }}</text>
				</view>
			</view>
			<view class="line"></view>
		</view>
	
		<!-- 商品信息 -->
		<view class="good-box back-grey-light">
			<!-- 菜单 -->
			<scroll-view scroll-y="true" scrollRightTop :scroll-into-view="itemId" :scroll-top="scrollTop"
				class="back-grey-light" :style="{height: scrollHeight+'px'}">
				<view style="padding-bottom: 150rpx;">
					<view v-for="(item, index) in goods" :key="index" class="row-box center prow-base cate-item"
					:class="cate==index?'':'back-white'" @click="swichMenu(index)">
						<text :class="cate==index?'bold primary':'grey-light'" style="text-align: center;">{{ item.name }}</text>
						<view v-show="cate==index" class="highlight"></view>
						<view v-if="menuCartNum(item.id)" class="radius-circle back-red row-box center number">
							<text class="s24 white">{{ menuCartNum(item.id) }}</text>
						</view>
					</view>
				</view>
			</scroll-view>
			<!-- 商品 -->
			<scroll-view scroll-y="true" scroll-with-animation :scroll-top="scrollRightTop" @scroll="rightScroll"
				:style="{height: scrollHeight+'px'}">
				<view style="padding-bottom: 150rpx;">
					<view v-for="(item, index) in goods" :key="index" class="col-box prow-base good-cate">
						
						<!-- 商品列表 -->
						<view class="">
							<!-- 标题 -->
							<view class="pcol-lg title-box">
								<text class="s26 bold">{{ item.name }}</text>
							</view>
							<!-- 商品项 -->
							<view v-for="(item2, index2) in item.goodsList" :key="index2" class="radius-l back-white pall-base good-item"
							:class="index2==item.goodsList.length-1?'':'gap'" @click="openDetail(item2)">
								<image class="radius-l image" :src="item2.img" mode="aspectFill"></image>
								<view class="col-box sb" style="height: 100%;">
									<text class="bold mb-4 limit2">{{ item2.name }}</text>
									<text v-if="item2.description" class="s24 grey-light limit2 mb-4">{{ item2.description }}</text>
									<view class="row-box sb">
										<view class="price-box row-box end">
											<text class="s24 bold" style="line-height: 24rpx;">￥</text>
											<text class="s32 bold" style="line-height: 32rpx;">{{ moneyFormat(item2.defaultSpec.price, 2) }}</text>
										</view>
										<view class="button-box">
											<view v-if="item2.spLists.length || item2.attLists.length" class="select-spec back-primary row-box center">
												<text class="s24 white">选规格</text>
												<view v-if="goodCartNum(item2.id)" class="radius-circle back-red row-box center number">
													<text class="s24 white">{{ goodCartNum(item2.id) }}</text>
												</view>
											</view>
											<view v-else class="row-box">
												<u-icon v-show="goodCartNum(item2.id)" name="minus-circle" color="#ccc" size="44" @tap.stop="changeGoodCartNumber(item2, -1)"></u-icon>
												<text v-if="goodCartNum(item2.id)" class="bold" style="display: block;width: 44rpx;text-align: center;">{{ goodCartNum(item2.id) }}</text>
												<u-icon name="plus-circle-fill" :color="primaryColor" size="44" @tap.stop="changeGoodCartNumber(item2, 1)"></u-icon>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 商品详情弹窗 -->
		<u-popup v-model="showGood" mode="center" border-radius="20" width="90%">
			<view class="good-pop">
				<view class="radius-circle row-box center close-box" @tap.stop="showGood=false">
					<u-icon name="close" color="#ffffff" size="32"></u-icon>
				</view>
				<image class="image" :src="good.img" mode="aspectFill"></image>
				<view class="prow-lg content-box">
					<view class="row-box">
						<text class="bold">{{ good.name }}</text>
					</view>
					<scroll-view scroll-y="true" style="height: 100%;">
						<view>
							<view class="col-box mb-l">
								<view class="row-box mb-m">
									<text class="s24 grey-light">商品描述</text>
								</view>
								<text class="s24 grey-dark">{{ good.description?good.description:'暂无描述' }}</text>
							</view>
							<!-- 属性 -->
							<view v-if="good.attLists.length" class="">
								<view v-for="(item, index) in good.attLists" :key="index" class="mb-l">
									<view class="row-box mb-m">
										<text class="s24 grey-light">{{ item.name }}</text>
									</view>
									<view class="spec-box">
										<view v-for="(item2, index2) in item.attrItemList" :key="index2" class="back-grey radius-base mr-base spec"
											:class="item2.isDefault?'back-primary':''" @click="changeAttrDefault(index, index2)">
											<text class="s24 grey-dark" :class="item2.isDefault?'white':''">{{ item2.name }}</text>
										</view>
									</view>
								</view>
							</view>
							<!-- 规格 -->
							<view v-if="good.spLists.length" class="mb-l">
								<view class="row-box mb-m">
									<text class="s24 grey-light">份量</text>
								</view>
								<view class="spec-box">
									<view v-for="(item, index) in good.spLists" :key="index" class="back-grey radius-base mr-base spec"
										:class="item.id==good.defaultSpec.id?'back-primary':''" @click="changeSpecDefault(index)">
										<text class="s24 grey-dark" :class="item.id==good.defaultSpec.id?'white':''">{{ item.name }} - ￥{{ moneyFormat(item.price, 2) }}</text>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
					<view class="col-box pcol-l sb bottom-box">
						<view class="row-box sb">
							<view class="col-box" :class="getGoodSelectedProps(good, 'text')?'sb':'mid'" style="height: 100%;">
								<view class="row-box end">
									<text class="s20 bold" style="line-height: 24rpx;">￥</text>
									<text class="s28 bold" style="line-height: 28rpx;">{{ moneyFormat(good.defaultSpec.price, 2) }}</text>
								</view>
								<text v-show="getGoodSelectedProps(good, 'text')" class="s24 grey-light">{{ getGoodSelectedProps(good, 'text') }}</text>
							</view>
							<view v-if="good.attLists.length || good.spLists.length" class="row-box">
								<u-icon v-show="good.num>0" name="minus-circle" color="#ccc" size="52" @tap.stop="changeCurrentGoodNumber(-1)"></u-icon>
								<text v-if="good.num>0" class="bold" style="display: block;width: 44rpx;text-align: center;">{{ good.num }}</text>
								<u-icon v-show="good.num<100" name="plus-circle-fill" :color="primaryColor" size="52" @tap.stop="changeCurrentGoodNumber(1)"></u-icon>
							</view>
						</view>
						<view class="row-box center back-primary add-button" @tap.stop="changeGoodCartNumber(good, good.num, 1)">
							<text class="white">加入购物车</text>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		
		<view v-show="showCart" class="cart-mask"
			@touchmove.stop.prevent="() => {}" hover-stop-propagation @click.stop="closeCart()">
		</view>
		<!-- 购物车悬浮 -->
		<view class="prow-lg cart-box">
			<view class="back-white radius-l pall-base cart">
				<!-- 头部 -->
				<view v-if="showCart" class="row-box sb" style="border-bottom: 2rpx solid #f0f0f0;">
					<view class="row-box">
						<text class="bold">已选商品</text>
						<view v-if="getCartBoxPrice" class="row-box">
							<text class="s24 grey-light" style="line-height: 28rpx;">
								（餐盒费：
								<text class="s24 red" style="line-height: 28rpx;">￥{{ getCartBoxPrice }}</text>
								）
							</text>
						</view>
					</view>
					<u-icon class="pcol-base" name="trash" color="#999" :size="28"
						label='清空购物车' label-size="24" label-pos="right" label-color="#999" margin-left="4" @tap.stop="clearCart()">
					</u-icon>
				</view>
				<!-- 购物车内容 -->
				<scroll-view v-if="showCart" scroll-y="true" class="mb-10">
					<view style="height: 520rpx;">
						<view	v-for="(item, index) in cart" :key="index" class="row-box sb end pcol-lg prow-base cart-item">
							<view class="row-box start">
								<image class="radius-l mr-base image" :src="item.goods.img" mode="aspectFill"></image>
								<view class="col-box" style="max-width: 260rpx;">
									<text class="bold limit2 mb-10">{{ item.goods.name }}</text>
									<text class="s24">{{ item.goodsAttrItemText?item.goodsAttrItemText:'默认规格' }}</text>
									<view class="row-box end">
										<text class="s20 bold" style="line-height: 24rpx;">￥</text>
										<text class="s28 bold" style="line-height: 28rpx;">{{ moneyFormat(item.goods.defaultSpec.price, 2) }}</text>
									</view>
								</view>
							</view>
							<view class="row-box">
								<u-icon v-show="item.num>0" name="minus-circle" color="#ccc" size="52" @tap.stop="changeGoodCartNumber(item, -1)"></u-icon>
								<text v-if="item.num>0" class="bold" style="display: block;width: 44rpx;text-align: center;">{{ item.num }}</text>
								<u-icon v-show="item.num<100" name="plus-circle-fill" :color="primaryColor" size="52" @tap.stop="changeGoodCartNumber(item, 1)"></u-icon>
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 底部购物车栏 -->
				<view class="row-box sb" @click="clickCart()">
					<view class="row-box mr-base">
						<view style="position: relative;">
							<view v-if="cart.length" class="back-red row-box center radius-circle" style="width: 32rpx;height: 32rpx;position: absolute;top: -8rpx;left: 24rpx;z-index: 9;">
								<text class="s24 white">{{ getCartGoodsNumber }}</text>
							</view>
							<image class="icon48" src="../static/购物车.png"></image>
						</view>
						<view class="row-box end">
							<text class="s24 bold" style="line-height: 24rpx;">￥</text>
							<text class="s32 bold" style="line-height: 32rpx;">{{ moneyFormat(getCartGoodsPrice, 2, '') }}</text>
						</view>
					</view>
					<view class="row-box center button" :class="disabledPay?'back-text-grey':'back-primary'" @tap.stop="goOrderSubmit()">
						<text class="white">{{ payText }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import mixinLinkage from "@/common/mixin_linkage.js"
	export default {
		mixins: [mixinLinkage],
		data() {
			return {
				merchant: {
					isColse: 0,
					givePrice: '15'
				}, // 店铺详情
				
				showGood: false, // 是否展示商品详情
				currentCateId: null,// 当前分类id
				currentCateName: '',// 当前分类名称
				good: {
					num: 1,
					defaultSpec: {},
					attLists: [],
					spLists: [],
				}, // 当前商品
				
				cart: [], // 购物车列表
				showCart: false, // 是否打开购物车
			};
		},
		computed: {
			menuCartNum() { // 计算同分类商品总数
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.goods.typeId === id) {
						return acc += cur.num
					}
					return acc
				}, 0)
			},
			goodCartNum() {	// 计算同id商品总数 -- 无视商品的规格属性
				return (id) => this.cart.reduce((acc, cur) => {
					if (cur.goods.id === id) {
						return acc += cur.num
					}
					return acc
				}, 0)
			},
			popCartNum() { // 计算同规格或同属性或同规格同属性商品总数--暂未使用
				return (good) => {
					if (good.spLists==false && good.attLists==false) { // 单规格+无多属性
						return this.cart.reduce((acc, cur) => {
							if (cur.goods.id === good.id) {
								return acc += cur.num
							}
							return acc
						}, 0)
					}else if (good.spLists && good.attLists==false) { // 多规格+无多属性
						return this.cart.reduce((acc, cur) => {
							if ((cur.goods.id === good.id) && (cur.goods.defaultSpec.id == good.defaultSpec.id)) {
								return acc += cur.num
							}
							return acc
						}, 0)
					} else if (good.spLists==false && good.attLists) { // 单规格+多属性
						return this.cart.reduce((acc, cur) => {
							if ((cur.goods.id === good.id) && (cur.goodsAttrItemIds == this.getGoodSelectedProps(good, 'id'))) {
								return acc += cur.num
							}
							return acc
						}, 0)
					} else if (good.spLists && good.attLists) { // 多规格+多属性
						return this.cart.reduce((acc, cur) => {
							if ((cur.goods.id === good.id) && (cur.goods.defaultSpec.id == good.defaultSpec.id) && (cur.goodsAttrItemIds == this.getGoodSelectedProps(good, 'id'))) {
								return acc += cur.num
							}
							return acc
						}, 0)
					}
				}
			},
			getCartGoodsNumber() { // 计算购物车总数
				return this.cart.reduce((acc, cur) => acc + cur.num, 0)
			},
			getCartGoodsPrice() {	// 计算购物车商品总价
				return this.cart.reduce((acc, cur) => {
					return acc + cur.num * (cur.goods.defaultSpec.price + cur.goods.defaultSpec.boxPrice)
				}, 0)
			},
			getCartBoxPrice() {	// 计算购物车餐盒费总价
				return this.cart.reduce((acc, cur) => acc + cur.num * cur.goods.defaultSpec.boxPrice, 0)
			},
			payButtonClass() { // 购物车按钮的类名
				if (this.merchant.isColse) { // 没营业
					return 'grey'
				} else { // 营业
					if (!this.merchant.givePrice && !this.getCartGoodsPrice) { // 达到起送价、起送价和商品总价是0元
						return 'grey'
					} else if (this.spread<=0) { // 达到起送价
						return 'primary'
					} else { // 没到起送价
						return 'grey'
					}
				}
			},
			payText() { // 购物车按钮文字
				if (this.merchant.isColse) { // 没营业
					return '已打烊'
				} else { // 营业
					if (!this.merchant.givePrice && !this.getCartGoodsPrice) { // 达到起送价、起送价和商品总价是0元
						return '还差￥0.00起送'
					} else if (this.spread<=0) { // 达到起送价
						return '去结算'
					} else { // 没到起送价
						return `还差￥${this.moneyFormat(this.spread, 2)}起送`
					}
				}
			},
			disabledPay() { // 是否禁止点击购买 没营业、不到起送价、起送价为0
				return this.merchant.isColse || (this.getCartGoodsPrice < this.merchant.givePrice) || (!this.merchant.givePrice && !this.getCartGoodsPrice)? true : false
			},
			spread() { // 差多少元起送
				return this.merchant.givePrice - this.getCartGoodsPrice
			}
		},
		onLoad(options) {
			uni.createSelectorQuery().in(this).select('.head-box').boundingClientRect(res => {
				// console.log(res.height)
				this.scrollHeight = uni.getSystemInfoSync().windowHeight - res.height
			}).exec()
			// 获取店铺详情
			this.getMerchantInfo()
			// 获取商品信息列表
			this.getGoodsList(options.userId)
		},
		methods: {
			// 点击商品项打开详情
			openDetail(good) {
				// 多规格1 非0
				let type = good.attLists.length ? 1 : 0
				// 设置当前规格详情的商品
				this.good = JSON.parse(JSON.stringify({...good, num: 1}))
				// 多属性商品
				if (type) {
					// 遍历所有属性对象增加新属性isDefault=0，即为非默认
					this.good.attLists.forEach(attr => {
						attr.attrItemList.forEach((value, index) => {
							if (index>0) {
								this.$set(value, 'isDefault', 0)
							} else {
								this.$set(value, 'isDefault', 1)
							}
						})
					})
				}
				this.showGood = true
			},
			// 点击规格项-改变当前多规格商品的默认规格值
			changeSpecDefault(index) {
				// 将选中的规格设为默认
				this.$set(this.good, 'defaultSpec', this.good.spLists[index])
			},
			// 点击属性项-改变当前多属性商品的默认属性值
			changeAttrDefault(index, index2) {
				// 遍历所有属性对象设置属性isDefault=0，即为非默认
				this.good.attLists[index].attrItemList.forEach(value => value.isDefault = 0)
				// 将选中的属性设为默认
				this.good.attLists[index].attrItemList[index2].isDefault = 1
			},
			// 商品详情弹窗内改变当前商品数量
			changeCurrentGoodNumber(num) {
				this.$set(this.good, 'num', this.good.num+num)
			},
			// 点击加入购物车
			addCart() {
				return uni.showToast({
					icon: 'none',
					title: '店铺打烊中！'
				})
			},
			// 点击无属性单规格商品的数量按钮/点击商品详情中的加入购物车-修改购物车中该商品数量
			changeGoodCartNumber(good, num, type=0) {
				if (num==0 && type==1) return uni.showToast({
					icon: 'none',
					title: '未选择商品数量！'
				})
				// 查找该商品在购物车中的下标
				let index = this.cart.findIndex(item => {
					return (item.goods.id === good.id) && (item.goods.defaultSpec.id == good.defaultSpec.id) && (item.goodsAttrItemIds == this.getGoodSelectedProps(good, 'id'))
				})
				if (index==-1) { // 未找到即新增
					let	propsId = this.getGoodSelectedProps(good, 'id')
					let	propsText = this.getGoodSelectedProps(good, 'text')
					let params = {
						num: num,
						spId: good.defaultSpec.id,
						goodsAttrItemIds: propsId,
						goodsAttrItemText: propsText,
						goods: {
							...good
						}
					}
					this.cart.push(params)
				} else { // 找到即数量增减
					this.cart[index].num += num
					if (this.cart[index].num==0) this.cart.splice(index, 1)
				}
				if (type) this.showGood = false
			},
			// 打开购物车
			clickCart() {
				if (!this.cart.length) return
				this.showCart = !this.showCart
			},
			// 关闭购物车
			closeCart() {
				this.showCart = false
			},
			// 清空购物车
			clearCart() {
				this.cart = []
				this.closeCart()
			},
			// 计算当前商品所选规格属性--文本或id的组合
			getGoodSelectedProps(good, type = 'text') {
				if (good.spLists==undefined || good.attLists==undefined) return ''
				// 无规格和无多属性的不需要计算所选规格属性
				if (good.spLists.length || good.attLists.length) { // 多规格或多属性
					// 需要计算所选规格属性文本和
					let props = []
					if (good.spLists.length && type === 'text') { // 有多规格则显示规格名称
						props.push(this.good.defaultSpec.name)
					}
					if (good.attLists.length) { // 有多属性则显示属性名称拼接属性id
						good.attLists.forEach(({attrItemList}) => {
							attrItemList.forEach(value => {
								if (value.isDefault) {
									props.push(type === 'text' ? value.name : value.id)
								}
							})
						})
					}
					return type === 'text' ? props.join('，') : props.join(',')
				}
				return ''
			},
			
			// 获取商品信息列表
			getGoodsList(userId) {
				this.$api.GetGoodsList({
					status: 0,
					userId: userId
				}).then(res => {
					console.log('GetGoodsList-success', res)
					if (res.data.code === 200) {
						this.goods = res.data.data
					}
				}).catch(err => {
					console.log('GetGoodsList-fail', err)
				})
			},
			// 获取店铺详情
			getMerchantInfo() {
				this.$api.GetMerchantInfo().then(res => {
					console.log('GetMerchantInfo-success', res)
					if (res.data.code === 200) {
						this.merchant = res.data.data
					}
				}).catch(err => {
					console.log('GetMerchantInfo-fail', err)
				})
			},
			
			// 前往提交订单页面
			goOrderSubmit() {
				let cart = this.cart.map(item => {
					return {
						spId: item.spId,
						num: item.num,
						goodsId: item.goods.id,
						attrItemList: item.goodsAttrItemIds
					}
				})
				uni.navigateTo({
					url: `/pages/subPackage/merchant/order_submit/order_submit?id=${this.merchant.id}&cart=${JSON.stringify(cart)}`
				})
			}
		},
	}
</script>

<style lang="scss">
	// 商家信息
	.info-box {
		box-sizing: border-box;
		padding: 28rpx 44rpx;
	}
	// 分割线
	.line {
		width: 100%;
		height: 2rpx;
		background-color: #f0f0f0;
	}
	// 商品信息
	.good-box {
		display: grid;
		grid-template-columns: 180rpx 1fr;
		//分类项
		.cate-item {
			box-sizing: border-box;
			height: 116rpx;
			position: relative;
			.highlight {
				position: absolute;
				top: 0;
				left: 0;
				z-index: 9;
				width: 8rpx;
				height: 116rpx;
				border-radius: 0 10rpx 10rpx 0;
				background: $uni-color-primary;
			}
			.number {
				position: absolute;
				top: 0;
				right: 0;
				z-index: 9;
				width: 32rpx;
				height: 32rpx;
			}
		}
		// 商品项
		.good-item {
			height: fit-content;
			display: grid;
			grid-template-columns: 184rpx 1fr;
			column-gap: 20rpx;
			align-items: center;
			box-shadow: 0 0 10rpx #eee;
			&.gap {
				margin-bottom: 30rpx;
			}
			.image {
				display: block;
				width: 184rpx;
				height: 184rpx;
			}
			.button-box {
				.select-spec {
					position: relative;
					width: 108rpx;
					height: 52rpx;
					border-radius: 24rpx;
					.number {
						position: absolute;
						top: -6rpx;
						right: -6rpx;
						z-index: 9;
						width: 32rpx;
						height: 32rpx;
					}
				}
			}
		}
	}
	
	// 商品详情弹窗
	.good-pop {
		position: relative;
		height: 100%;
		display: grid;
		grid-template-rows: 380rpx 1fr;
		.close-box {
			padding: 16rpx;
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			z-index: 9;
			background: rgba(0, 0, 0, 0.3);
		}
		.image {
			display: block;
			width: 100%;
			height: 380rpx;
		}
		.spec-box {
			display: flex;
			flex-wrap: wrap;
			.spec {
				padding: 4rpx 16rpx;
			}
		}
		.content-box {
			height: 100%;
			display: grid;
			grid-template-rows: 64rpx 388rpx 208rpx;
			.bottom-box {
				box-sizing: border-box;
				.add-button {
					width: 100%;
					height: 80rpx;
					border-radius: 40rpx;
				}
			}
		}
	}
	
	// 购物车遮罩
	.cart-mask {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 98;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.3);
	}
	// 购物车悬浮
	.cart-box {
		width: 100%;
		position: absolute;
		left: 0;
		bottom: 20rpx;
		z-index: 99;
		.cart {
			box-shadow: 0 0 10rpx #ccc;
			
			// 购物车内容
			.cart-item {
				border-bottom: 2rpx solid #f0f0f0;
				&:last-child {
					border-bottom: none;
				}
				.image {
					width: 160rpx;
					height: 160rpx;
				}
			}
		}
		.button {
			width: 280rpx;
			height: 72rpx;
			border-radius: 36rpx;
			
		}
	}
</style>
